package com.ly.share.juc.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author icanci
 * @since 1.0 Created in 2022/06/05 22:45
 */
public class AbaDemo3 {
    private static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference(1, 1);

    public static void main(String[] args) {

        new Thread(() -> {
            int oldReference = atomicStampedReference.getReference();
            int newReference = oldReference + 1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int stamp = atomicStampedReference.getStamp();
            int newStamp = stamp + 1;
            boolean res = atomicStampedReference.compareAndSet(oldReference, newReference, stamp, newStamp);
            System.out.println(Thread.currentThread().getName() + " " + res);
        }, "t1").start();

        new Thread(() -> {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Integer reference = atomicStampedReference.getReference();
            int stamp = atomicStampedReference.getStamp();
            boolean b = atomicStampedReference.compareAndSet(reference, reference + 1, stamp, stamp + 1);
            boolean b1 = atomicStampedReference.compareAndSet(reference + 1, reference, stamp + 1, stamp + 1 + 1);

            System.out.println(Thread.currentThread().getName() + " incre: " + b + ",decre: " + b1);
        }, "t1").start();
    }
}
